from django.apps import AppConfig
from django.conf import settings
from django.urls import register_converter
from sqids import Sqids

class SqidsConverter:
    regex = f"[a-zA-Z0-9]{settings.SQIDS_MIN_LENGTH,}"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sqids = Sqids(
            alphabet=settings.SQIDS_ALPHABET,
            min_length=settings.SQIDS_MIN_LENGTH,
            blocklist=settings.SQIDS_BLOCKLIST,
        )

    def to_python(self, value):
        return self.sqids.decode(value)

    def to_url(self, value):
        return self.sqids.encode(value)


class SingleSqidsConverter:
    regex = r"[a-zA-Z0-9]{" + str(settings.SQIDS_MIN_LENGTH) + r",}"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sqids = Sqids(
            alphabet=settings.SQIDS_ALPHABET,
            min_length=settings.SQIDS_MIN_LENGTH,
            blocklist=settings.SQIDS_BLOCKLIST,
        )

    def to_python(self, value):
        id_list = self.sqids.decode(value)
        if len(id_list) != 1:
            raise ValueError(f"{value} is not a single sqids")
        return id_list[0]

    def to_url(self, value):
        if not isinstance(value, int) or value < 0:
            raise ValueError(f"{value} can not encode as a single sqids")
        return self.sqids.encode([value])

class JournalConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'journal'
    
    def ready(self):
        register_converter(SqidsConverter, "sqids")
        register_converter(SingleSqidsConverter, "single_sqids")
